import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {BookPage} from "../book/book";
import {Http} from "@angular/http";
import {parser} from '../../engine/findengine'

@Component({
  selector: 'page-search',
  templateUrl: 'search.html'
})
export class SearchPage {
  searchQuery: string = '';
  items: Array<{title: string, note: string, logo: string, url: string}>;

  constructor(public navCtrl: NavController, public navParams: NavParams,public http: Http) {
    this.initializeItems();
  }

  initializeItems() {
    this.items = [];
  }

  getItems(ev: any) {
    let val = ev.target.value;
    console.log(val);

    if (val && val.trim() != '') {
      let url = parser.searchUrl;
      let url_1 = url.replace('@key',encodeURI(val.trim()));
      console.log(url_1);
      this.http.get(url_1)
        .subscribe(data => {
          let books:Array<{name:string,logo:string,url:string}> ;
          books = JSON.parse(parser.search_parse(data.url, data.text()));
          for (let i = 0; i < books.length; i++) {
            this.items.push({
              title: books[i].name,
              note: 'This is item #' + i,
              logo: books[i].logo,
              url: books[i].url
            });
          }
        }, error => {
          console.log(JSON.stringify(error.json()));
        });// end http.get

    }
  }

  itemTapped(event, item) {
    this.navCtrl.push(BookPage, {
      item: item
    });
  }

}
